"""
给策略函数使用，用于股票列表，指标输出
"""
import tushare as ts
import pandas as pd
import time
import datetime
import os
import pandas as pd
import numpy as np


# pd.options.mode.chained_assignment = None #avoid :pandas SettingWithCopyWarning

ts.set_token("6667cd4a2326f2f937062a0f4fb59aea5c56d13b1f6f26225f115fe9")
pro = ts.pro_api()

def n_days_before(st_day,n):
    """
    st_day:开始日期
    :type st_day: datetime.date | datetime.datetime
    """
    from  chinese_calendar  import is_holiday
    while(n>0):
        if not is_holiday(st_day):
            n=n-1
        st_day=st_day-datetime.timedelta(1)
    return st_day

def get_data(code,N=60):
    days=N
    end_date_str=time.strftime("%Y%m%d")
    end_datetime = datetime.datetime.strptime(end_date_str, '%Y%m%d') 
    start_datetime=n_days_before(end_datetime,days)
    start_date_str=start_datetime.strftime("%Y%m%d")
    if isinstance(code,int):
        code6=str(code).zfill(6)
        if code6[:2]!="60":
            code_str='{}.SZ'.format(code6)
        else:
            code_str='{}.SH'.format(code6)
    else:
        code_str=code
    try:
        df = pro.daily(ts_code=code_str, start_date=start_date_str, end_date=end_date_str)      
    except Exception as e:
        print(e) #500/min
        time.sleep(61) 
        df = pro.daily(ts_code=code_str, start_date=start_date_str, end_date=end_date_str)  
    # print(df)     
    df['date'] = df['trade_date'].map(lambda ts_date: datetime.datetime.strptime(ts_date,'%Y%m%d') )
    df.set_index('date',inplace=True)
    df.sort_index(inplace=True)  
    df.drop(columns=['trade_date'],inplace=True)
    df.rename(columns={"open":"Open","high":"High","low":"Low","close":"Close",'vol': 'Volume',"amount":"Amount"},inplace=True)
    return df[["Open","High","Low","Close","Volume","Amount"]]

def multi_thread_check(file_name,code_list,stratedy):
    """
    使用线程池，由系统自动分配线程数量，并打印线程目标函数的返回结果
    """  
    #在append之前先删除原数据表
    import concurrent.futures

    with concurrent.futures.ThreadPoolExecutor() as executor:     
        results=[ executor.submit(stratedy,i,file_name) for i in code_list]
        for f in concurrent.futures.as_completed(results):
            print(f.result()) 


def sort_stratedy(stratedy,ascending=True):
    stratedy_name=stratedy.__name__
    path=os.getcwd()
    df=pd.read_csv(path+'/f10_true.csv')
    code_index_list=df['code'].to_list()
    # file_name="{}.csv".format("chao_di_shen_zhen"+str(time.strftime("%Y_%m_%d_%H")))
    file_name="./Result/%s.csv"%stratedy_name
    if os.path.exists(file_name): os.remove(file_name)
    output_File = open(file_name,'a+')
    output_File.write('{},{},{}\n'.format('code',stratedy_name,'close'))
    output_File.flush()
    multi_thread_check(file_name,code_index_list,stratedy)  
    #zljc由大到小排序
    df_res=pd.read_csv(file_name,encoding='unicode_escape') 
    df_res.columns=['code',stratedy_name,'close']
    df_res.sort_values(by=stratedy_name,ascending=ascending,inplace=True)
    df_res.to_csv(file_name)

def gene_code_list():
    data_1 = pro.stock_basic(exchange='', list_status='L', market="主板",fields='ts_code,name,area,industry,list_date') #'ts_code,name,area,industry,list_date')
    data_2 = pro.stock_basic(exchange='', list_status='L', market="中小板",fields='ts_code,name,area,industry,list_date') #'ts_code,name,area,industry,list_date')  
    target_symbols = data_1.append(data_2, ignore_index=True) 
    target_symbols.to_csv("main_stock.csv")

def send_to_email(file_name,filepath_str): #filepath_str:'C:\1.txt'
    """send_to_email(fn,path+fn)"""
    import yagmail
    # 登录你的邮箱
    yag = yagmail.SMTP(user = 'jamal121@163.com', password = 'kirin107105', host = 'smtp.163.com')
    # 发送邮件
    yag.send(to = ['jamal121@163.com'], subject = file_name, contents = ['股票',filepath_str])


def draw_(df,*args):

    #画图
    import mplfinance as mpf
    from color_dict import color_
    add_plot=[]
    for index,arg in enumerate(args):
        # rrgg:int=index*256
        # bbaa:int=index+30
        # rrggbbaa:int=(rrgg<<16)+bbaa #int overflow to be long,python3 no long,only in python2
        # rrggbbaa_str='#'+(str(hex(rrggbbaa)).split('x')[-1]).zfill(8)
        # print(color_().values())
        rrggbbaa = list(color_().values())[index]
        add_plot.append(mpf.make_addplot(arg,color=rrggbbaa)) ##rrggbbaa
    my_color = mpf.make_marketcolors(up='red',down='green',volume='inherit',inherit=True)
    my_style = mpf.make_mpf_style(
        facecolor = 'white',
        marketcolors = my_color,
        gridaxis='horizontal',
        gridcolor='#030303ff',
        gridstyle='-',
        y_on_right=False
    )
    mpf.plot(df,
            addplot=add_plot,
            type='candle',
            style=my_style,
            figratio=(5,3),
            figscale=2,
            volume=True,
            savefig='./Result/s000799.png'
    )


if __name__=='__main__':
#   print(get_data(799,10))
    # gene_code_list()
    path=os.getcwd()
    # df=pd.read_csv(path+'/f10_true.csv')
    # code_index_list=df['code'].to_list()
    # df=pd.read_csv(path+'/main_stock.csv')
    fn="./Result/cdsz.csv"
    # send_to_email(fn,path+fn)
